package com.yoomiito.app.utils;

import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Message;

import com.yoomiito.app.Constant;
import com.yoomiito.app.interf.OnDownloadListener;
import com.yoomiito.app.model.bean.VersionInfo;
import com.yoomiito.app.net.YmApi;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class DownloadUtils {



    public static void download(String path, String downloadUrl, OnDownloadListener listener){

        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }else {
           file.getParentFile().mkdirs();
        }
        YmApi.downApk().download(downloadUrl)
                .subscribeOn(Schedulers.io())
                .map(new Function<ResponseBody, File>() {
                    @Override
                    public File apply(ResponseBody responseBody) throws Exception {

                        try {
                            FileOutputStream fos = new FileOutputStream(file);
                            byte[] buf = new byte[2048];
                            int len = 0;
                            InputStream inputStream = responseBody.byteStream();
                            while ((len = inputStream.read(buf)) != -1) {
                                fos.write(buf, 0, len);
                            }
                            inputStream.close();
                            fos.close();

                        } catch (FileNotFoundException e) {
                        } catch (IOException e){
                        }
                        return file;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) throws Exception {
                        if (listener!=null)listener.result(file);
                    }
                });
    }

    private static DownloadUtils downloadUtil;
    private final OkHttpClient okHttpClient;

    public static DownloadUtils get() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtils();
        }
        return downloadUtil;
    }

    private DownloadUtils() {
        okHttpClient = new OkHttpClient();
    }

    public static ArrayList<String> getFileName(String fileAbsolutePaht, String type) {
        ArrayList<String> result = new ArrayList<String>();
        File file = new File(fileAbsolutePaht);
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; ++i) {
            if (!files[i].isDirectory()) {
                String fileName = files[i].getName();
                if (fileName.trim().toLowerCase().endsWith(type)) {
                    result.add(fileName);
                }
            }
        }
        return result;
    }

    /**
     * 查询音频文件是否存在本地
     *
     * @param name 文件名称如11.mp3
     * @param path 存储路径 如/storage/emulated/0/1video
     * @param type 类型 .mp3 .mp4
     * @return
     */
    public static boolean fileIsExists(String name, String path, String type) {
        //这个方法是获取内部存储的根路径
        boolean pdtemp = false;

        ArrayList<String> ss = getFileName(path, type);
        for (String s : ss) {
            if (s.equals(name)) pdtemp = true;
        }
        File file = new File(name);
        System.out.println(file);
        if (!pdtemp) {// 文件不存在
            return false;
        }
        return true;
    }

    /**
     * @param url          下载连接
     * @param destFileDir  下载的文件储存目录
     * @param destFileName 下载文件名称
     * @param listener     下载监听
     */
    public void download(final String url, final String destFileDir,
                         final String destFileName, final OnDownloadListener1 listener) {
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败监听回调
                listener.onDownloadFailed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                File dir = new File(destFileDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, destFileName);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中更新进度条
                        listener.onDownloading(progress);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess(file);
                } catch (Exception e) {
                    listener.onDownloadFailed(e);
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    public interface OnDownloadListener1 {
        /**
         * @param file 下载成功后的文件
         */
        void onDownloadSuccess(File file);

        /**
         * @param progress 下载进度
         */
        void onDownloading(int progress);

        /**
         * @param e 下载异常信息
         */
        void onDownloadFailed(Exception e);
    }
}
